class ApplicationController < ActionController::Base
  protect_from_forgery
  
  before_filter :set_i18n_locale_from_params
  before_filter :set_controller_and_action_names

  
  private 
  
  # adds the name of the current controller and the current action to the view
  def set_controller_and_action_names
      @current_controller = controller_name
      @current_action     = action_name
    end
  
  # loads the current cart or creates a fresh new cart for the session
  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart    
  end
  
  # loads the current checkout or creates a fresh checkout for the session
  def current_checkout
    Checkout.find(session[:checkout_id])
  rescue ActiveRecord::RecordNotFound
    checkout = Checkout.create
    session[:checkout_id] = checkout.id
    checkout    
  end
  
  protected
  
  # filter method for pages who need authorization
  def authorize
    unless User.find_by_id(session[:user_id])
      redirect_to login_url, notice: "Please log in"
    end
  end 
  
  # sets the locale from the parameters or loads default locale
  def set_i18n_locale_from_params
    if params[:locale]
      if I18n.available_locales.include?(params[:locale].to_sym)
        I18n.locale = params[:locale]
      end
    end
  end
    
  # field with default locale
  def default_url_options
    { locale: I18n.locale }
  end
end
